#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>
#include "StdSem.h"


struct StdSem 
{
    int semID;
};
Sem *InitSem(const char *__pathname, int __proj_id)
{
    Sem *s = (Sem*)malloc(sizeof(Sem));
    if(s == NULL)
        return NULL;

    key_t key = ftok(__pathname,__proj_id);
    if(key < 0)
    {
        perror("ftok");
        return NULL;
    }

    s->semID = semget(key,1,IPC_CREAT | 0777);
    if(s->semID < 0)
    {
        perror("semget");
        return NULL;
    }

    if(semctl(s->semID,0,SETVAL,1) < 0)
    {
        perror("semctl");
        return NULL;
    }
    return s;
}

void semPV(int SemID,int op)
{
    struct sembuf sembf;
    sembf.sem_op = op;
    sembf.sem_num = 0;
    sembf.sem_flg = SEM_UNDO;
    semop(SemID,&sembf,1);
}

void semP(Sem *s)
{
    semPV(s->semID,-1);
}

void semV(Sem *s)
{
    semPV(s->semID,1);
}

void ClearSem(Sem *s)
{
    if(s == NULL)
        return;

    semctl(s->semID,0,IPC_RMID,NULL);
    free(s);
}
